// pages/gjIndex/orderDetail/paymentItems.js
import config from '../../config.js';
var util = require('../../utils/util.js');
//qqmap-wx-jssdk.min.js
// 引入SDK核心类
var QQMapWX = require('../components/qqmap-wx-jssdk.min.js');

// 实例化API核心类
var map = new QQMapWX({
  key: 'D2KBZ-BTFHF-PNCJN-NFUUW-K4G56-DNFBW' // 必填
});
const base = config;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    polyline: [],
    orderId: null,
    typeId: null,
    order: null,
    payItems: [],
    totalOrPrice: 0.00,
    totalPrice: 0.00,
    couponItemList: [],
    coupon: null,
    tip: '',
    recordId: null,

    latitude: null,
    longitude: null,
    tolatitude: null,
    tolongitude: null,
    speed: null,
    accuracy: 6,
    key: "D2KBZ-BTFHF-PNCJN-NFUUW-K4G56-DNFBW",
    pickPath: null,
    sendPath: null,
    isShowMap: false,
    resultPick: {},
    resultSend: {},
    isNeedPay: true,
    isCanNotPay: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var orderId = options.orderId;
    var typeId = options.typeId;
    var isShowMap = false;

    if (typeId == 4 || typeId == 5) {
      isShowMap = true;
    }

    this.setData({
      orderId: orderId,
      typeId: typeId,
      isShowMap: isShowMap
    })

    this.loadOrderData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var coupon = wx.getStorageSync("coupon");
    if (coupon != null) {
      console.log(coupon);

      this.onCouponSet(coupon);
      wx.setStorageSync("coupon", null);
    } else {
      // this.loadOrderData();
    }
  },
  loadPoylineData: function() {
    var that = this;
    //获取支付项目
    wx.request({
      url: base.getPoyline,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        orderId: that.data.orderId,
        index: 4
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          if (res.data.data != null) {
            that.setData({
              paths: res.data.data
            })

            var points = [];
            var paths = res.data.data;
            if (paths != null && paths.length > 0) {
              //将解压后的坐标放入点串数组pl中
              var pl = [];
              for (var i = 0; i < paths.length; i++) {
                var item = paths[i];
                if (item.carSenType.typeId == 1) {
                  that.setData({
                    "pickPath.start": item,
                    latitude: item.lat,
                    longitude: item.lng,
                  })
                } else if (item.carSenType.typeId == 2) {
                  that.setData({
                    "pickPath.end": item
                  })
                } else if (item.carSenType.typeId == 3) {
                  that.setData({
                    "sendPath.start": item,
                    latitude: item.lat,
                    longitude: item.lng,
                  })
                } else if (item.carSenType.typeId == 4) {
                  that.setData({
                    "sendPath.end": item
                  })
                }
              }

            }


            that.setData({
              isShowMap: true,
            })

            that.calculateDinstance(that.data.pickPath, 1);
            that.calculateDinstance(that.data.sendPath, 2);
            that.driving(that.data.pickPath, '#FF0000DD');
            that.driving(that.data.sendPath, '#137AF0');
          }

        }
      }

    })
  },
  onCouponSet: function(item) {
    if (item != null && item.memberRights != null) {
      var totalPrice = this.data.totalOrPrice;
      console.log(totalPrice + "---")
      //折算
      var tip = '';
      if (item.memberRights.memberRightType.typeId == 1) {
        //次数
        tip = "" + totalPrice + "-" + item.memberRights.price + "=";
        if (totalPrice > item.memberRights.price) {
          totalPrice -= item.memberRights.price;
        } else {
          totalPrice = 0;
        }
      } else {
        //折扣
        tip = "" + totalPrice + "*" + item.memberRights.price + "折=";
        totalPrice = this.data.totalOrPrice * item.memberRights.price / 10;
      }
      totalPrice = util.numberFormat(totalPrice, 2);

      //设置是否可支付
      var isNeedPay = true;
      if (totalPrice == 0.0) {
        isNeedPay = false;
      }


      this.setData({
        tip: tip,
        coupon: item,
        totalPrice: totalPrice,
        isNeedPay: isNeedPay
      })
    }


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    wx.setStorageSync("coupon", null);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  loadOrderData: function() {
    var that = this;
    wx.showLoading({
      title: '数据加载中...',
    })
    //获取支付项目
    wx.request({
      url: base.orderDetailUrl,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        id: that.data.orderId
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          var order = res.data.data.order;
          var status = order.orderStatus;
          //判断是否需要支付
          var isCanNotPay = status.statusId == 6 ? true : false;

          that.setData({
            order: order,
            isCanNotPay: isCanNotPay
          })

          that.loadData();

        } else {
          wx.showToast({
            title: '订单信息获取失败',
            icon: 'none',
            duration: 1500
          })
          return false;
        }


      }

    })
  },
  loadData: function() {
    var that = this;
    //获取支付项目
    wx.request({
      url: base.getOrderPayItemList,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        typeId: this.data.typeId,
        orderId: that.data.orderId,
        price: that.data.totalPrice,

      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          if (res.data.data != null) {
            var totalPrice = util.numberFormat(res.data.totalPrice, 2);
            that.setData({
              payItems: res.data.data,
              totalPrice: totalPrice,
              totalOrPrice: totalPrice,
            })

            that.loadCouponList();
            that.loadPoylineData();
          }

        }

        wx.hideLoading();
      }

    })
  },
  loadCouponList: function() {
    var that = this;
    //获取支付项目
    wx.request({
      url: base.getCouponList,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      data: {
        typeId: this.data.typeId,
        orderId: that.data.orderId
      },
      method: "POST",
      success: function(res) {
        console.log(res.data);
        if (res.data.status == 200) {
          if (res.data.data != null) {
            console.log(res.data.data);
            for (var i = 0; i < res.data.data.length; i++) {
              var item = res.data.data[i];
              if (item.memberRights != null && item.memberRights.memberRightType.typeId == 2) {
                item.memberRights.price = util.numberFormat(item.memberRights.price * 10, 2);
                res.data.data[i] = item;
              }

            }
            that.setData({
              couponItemList: res.data.data,
            })

            that.onCouponSet(res.data.data[0]);
          }

        } else {}
      }

    })
  },
  //支付：
  payAction: function() {
    var that = this
    //禁止再次发起支付
    that.setData({
      isCanNotPay:true
    })
    //判断价格
    if (that.data.totalPrice <= 0) {
      that.payResult("");
    } else {
      var openId = wx.getStorageSync("openID");

      //判断openId是否为空
      //判断openId是否存在
      if (openId == null || openId == "") {
        wx.login({
          success: function(res) {
            wx.request({
              url: base.CheckOpenId,
              data: {
                code: res.code
              },
              success: function(res) {
                console.log("openId" + res.data.data.openid);
                wx.setStorageSync('openID', res.data.data.openid);
                // if (wx.getStorageSync("session") == null) {
                //   wx.setStorageSync("session", res.data.session);
                //   console.log("session:" + res.data.session);
                // }
                openId = res.data.data.openid;
                that.payOrder(openId);

              }
            })
          }
        })
      } else {
        that.payOrder(openId);
      }

    }

  },
  payOrder: function(openId) {
    var that = this;
    var orderId = that.data.orderId;
    console.log(orderId);
    wx.showLoading({
      title: '发起支付...',
    })
    wx.request({
      url: base.ordePayOrder,
      data: {
        //用户的openid
        openId: openId,
        price: 0.01,
        orderId: that.data.orderId,
        recordId: that.data.coupon == null ? -1 : that.data.coupon.recordId
      },
      success: function(result) {
        console.log(result);
        wx.hideLoading();
        if (result.data.status == 200) {
          //out_trade_no=res.data['out_trade_no'];
          wx.requestPayment({
            timeStamp: result.data.timeStamp,
            nonceStr: result.data.nonceStr,
            package: result.data.package,
            signType: 'MD5',
            paySign: result.data.paySign,
            success: function(successret) {
              console.log('支付成功');
              //获取支付用户的信息
              wx.showLoading({
                title: '支付成功！',
              })
              setTimeout(function() {
                that.payResult(result.data.orderNo);
                wx.hideLoading();
              }, 300);

            },
            fail: function(res) {
              that.loadOrderData();
              wx.showToast({
                title: '支付已取消！',
                icon: 'none',
                duration: 1000
              })
            }
          })
        } else {
          console.log();
        }
      }
    })
  },
  payResult: function(No) {
    if (No == null) {
      No = "";
    }
    var that = this;
    wx.showLoading({
      title: '更新订单...',
    })
    wx.request({
      url: base.orderPayConfirm,
      data: {
        orderNo: No,
        orderId: that.data.orderId,
        recordId: that.data.coupon == null ? -1 : that.data.coupon.recordId,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': wx.getStorageSync("session")
      },
      success: function(result) {
        console.log(result);
        wx.hideLoading();
        if (result.data.status == 200) {
          wx.showLoading({
            title: '订单支付成功',
          })
          // that.loadData();
          setTimeout(function() {
            /** wx.navigateBack({
               delta: 1
             })**/
            wx.setStorageSync("orderId", that.data.orderId);
            wx.setStorageSync("orderConfirmType", 1);
            var orderId = wx.getStorageSync("orderId");
            /**wx.switchTab({
              url: "../order/order"
            })**/
            wx.navigateTo({
              url: '../orderSuccess/success?id=' + orderId + "&tip=费用支付完成",
            })
          }, 1000);

        } else if (result.data.status == 201) {
          //订单更新失败；
          //记录当前订单OrderId;
          // wx.setStorageSync("payError", id);
          wx.showLoading({
            title: '订单支付失败',
          })
        }
      }
    })
  },
  engineNumberInput: function(e) {
    console.log(e);
    var item = e.currentTarget.dataset.item;
    var value = e.detail.value;
    item.price = value;
    this.setPayItem(item);
  },
  setPayItem: function(item) {
    var data = this.data.payItems;
    for (var i = 0; i < data.length; i++) {
      var it = data[i];
      if (it.itemId == item.itemId) {
        data[i] = item
      }
    }

    this.setData({
      payItems: data
    })
  },
  chooseCoupon: function() {
    var orderId = this.data.orderId;
    var typeId = this.data.typeId;
    wx.navigateTo({
      url: './coupomItems?orderId=' + orderId + "&typeId=" + typeId,
    })
  },
  planningAction: function() {
    wx.navigateTo({
      url: '../map/planningMap',
    })
  },
  //事件回调函数
  driving: function(point, color) {
    var _this = this;
    if (point != null && point.start != null) {
      var from = "" + point.start.lat + "," + point.start.lng;
      var to = "" + point.end.lat + "," + point.end.lng;
      var key = _this.data.key;
      var url = 'https://apis.map.qq.com/ws/direction/v1/driving/?from=' + from + '&to=' + to + '&key=' + key;
      console.log(url);
      //网络请求设置
      var opt = {
        //WebService请求地址，from为起点坐标，to为终点坐标，开发key为必填
        url: url,
        method: 'GET',
        dataType: 'json',
        //请求成功回调
        success: function(res) {
          var ret = res.data
          if (ret.status != 0) return; //服务异常处理
          var coors = ret.result.routes[0].polyline,
            pl = [];
          //坐标解压（返回的点串坐标，通过前向差分进行压缩）
          var kr = 1000000;
          for (var i = 2; i < coors.length; i++) {
            coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
          }
          //将解压后的坐标放入点串数组pl中
          for (var i = 0; i < coors.length; i += 2) {
            pl.push({
              latitude: coors[i],
              longitude: coors[i + 1]
            })
          }
          //设置polyline属性，将路线显示出来
          var polyline = _this.data.polyline;
          polyline.push({
            points: pl,
            color: color,
            width: 4
          });

          _this.setData({
            isShowMap: true,
            polyline: polyline
          })
        }
      };
      wx.request(opt);
    }
  },
  calculateDinstance: function(path, type) {
    var that = this;
    if (path != null && path.start != null) {
      // 调用接口
      map.calculateDistance({
        mode: 'driving',
        from: {
          latitude: path.start.lat,
          longitude: path.start.lng
        },
        to: [{
          latitude: path.end.lat,
          longitude: path.end.lng
        }],
        success: function(res) {
          console.log(res);
          that.setResultData(res.result.elements, type);


        },
        fail: function(res) {
          console.log(res);
        },
        complete: function(res) {
          console.log(res);
        }
      });
    }

  },
  setResultData: function(res, type) {
    console.log(res);
    var that = this;
    if (res != null && res.length > 0) {
      var item = res[0];
      var result = {};
      result['distance'] = item.distance;
      result['duration'] = util.formatSeconds(item.duration);
      if (type == 1) {
        that.setData({
          resultPick: result
        })

      } else {

        that.setData({
          resultSend: result
        })
      }
    }

  }
})